package cn.jcet.mapreduce.tables;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;

/**
 * @author 鲜磊
 * @Date 2020/12/16 10:50
 */
public class TablesReduce extends Reducer<Text,TableBean,TableBean,NullWritable> {

    @Override
    protected void reduce(Text key, Iterable<TableBean> values, Context context) throws IOException, InterruptedException {
        // 创建一个订单编号集合
        ArrayList<TableBean> orderList = new ArrayList<>();
        // 创建一个产品对象
        TableBean bean = new TableBean();

        // 对values进行遍历
        for (TableBean tableBean : values) {
            // 对标志位进行对比，查看是否为定位
            if ("order".equals(tableBean.getFlag())){
                TableBean orderBean = new TableBean();
                try {
                    BeanUtils.copyProperties(orderBean,tableBean);
                    // 添加到集合中去
                    orderList.add(orderBean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }else {
                // 产品表
                try {
                    BeanUtils.copyProperties(bean,tableBean);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        // 表的拼接
        for (TableBean tableBean1 : orderList) {
            tableBean1.setPname(bean.getPname());
            context.write(tableBean1,NullWritable.get());
        }
    }
}
